﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;
using System.Configuration;
using System.Data;

namespace AllNations.UI
{
    public partial class Fileshare : MakeItWebPage, IDynamicPage
    {
        public string SectionCd
        {
            get
            {
                return MakeItWebPage.GetQueryString("PageCd") ?? "Main";
            }
        }

        public override string SelectedSection
        {
            get
            {
                if (SectionCd == "Main")
                    return "Fellowship";
                else if (SectionCd == "SeekingTruth")
                    return "Education";
                else if (SectionCd == "MissionNews")
                    return "Mission";

                return string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RegisterAdminFunction("Share new file", "javascript:ShareNewFile();void(0);", "~/Images/btn-plus.gif");
            }
            lblErrorMesg.Text = string.Empty;
        }

        protected void btSaveNewFile_Click(object sender, EventArgs e)
        {
            if (IsPageAdministrator() && fuNewFile.UploadedFiles.Count > 0)
            {
                try
                {
                    if (txtFileTitle.Text.Trim() == "Error")
                        throw new ApplicationException("Intentional error.");

                    Guid guidFileshareId = Guid.NewGuid();

                    string sFilename = GetFileshareFilename(guidFileshareId, true);

                    fuNewFile.UploadedFiles[0].SaveAs(sFilename);

                    StoredProcArgs args = new StoredProcArgs();
                    args["pFileshareId"] = guidFileshareId;
                    args["pHtmlPageId"] = CurrentHtmlPage.HtmlPageId;
                    args["pSubjectTxt"] = txtFileTitle.Text.Trim();
                    args["pContentType"] = fuNewFile.UploadedFiles[0].ContentType;
                    //if (!string.IsNullOrEmpty(txtFileDescription.Text.Trim()))
                    //    args["pDescriptionTxt"] = txtFileDescription.Text.Trim();
                    args["pFilename"] = fuNewFile.UploadedFiles[0].FileName;
                    args["pSectionCd"] = SectionCd;
                    GenericCud.ExecuteCud("proc_cm_SaveFileshare", args);
                    txtFileTitle.Text = string.Empty;
                }
                catch (Exception ex)
                {
                    lblErrorMesg.Text = string.Format("Error saving new file: {0}", ex.Message);
                    panelAddNewFile.Style["display"] = "block";
                }
            }
        }

        private string GetFileshareFilename(Guid guidFileshareId, bool bCreateFolder)
        {
            string sFileRoot = string.Format(@"{0}\{1}",
                Server.MapPath(ConfigurationManager.AppSettings["FileshareRoot"]),
                CurrentHtmlPage.HtmlPageId);

            if (!System.IO.Directory.Exists(sFileRoot))
            {
                if (bCreateFolder)
                    System.IO.Directory.CreateDirectory(sFileRoot);
                else
                    throw new ApplicationException(string.Format("The folder does not exist: {0}", sFileRoot));
            }

            string sFilename = string.Format(@"{0}\{1}{2}",
                sFileRoot,
                guidFileshareId,
                fuNewFile.UploadedFiles[0].GetExtension());

            return sFilename;
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            StoredProcArgs args = new StoredProcArgs();
            Guid guidFileshareId = new Guid((sender as LinkButton).CommandArgument);
            args["pFileshareId"] = guidFileshareId;

            using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetFileshare", args))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    try
                    {
                        string sFilename = GetFileshareFilename(guidFileshareId, false);
                        System.IO.File.Delete(sFilename);
                    }
                    catch (Exception)
                    {
                        //ignore this exception
                    }

                    args["pHtmlPageId"] = CurrentHtmlPage.HtmlPageId;
                    args["pSectionCd"] = SectionCd;
                    GenericCud.ExecuteCud("proc_cm_DeleteFileshare", args);
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            StoredProcArgs args = new StoredProcArgs();
            args["pHtmlPageId"] = CurrentHtmlPage.HtmlPageId;
            string sSectionCd = SectionCd;
            args["pSectionCd"] = sSectionCd;
            rptFileShare.DataSource = GenericQry.GetDataSet("proc_cm_ListFileshare", args);
            rptFileShare.DataBind();
            HeaderImage1.Visible = true;

            switch (sSectionCd)
            {
                case "Main":
                    LeftNavigationChoice.SelectedIndex = viewMain.Index;
                    imgContentTitleBar.ImageUrl = "~/Images/titleSundayBulletin.png";
                    break;
                case "SeekingTruth":
                    LeftNavigationChoice.SelectedIndex = viewSeekingTruth.Index;
                    var sitemapMenu = radEducationMenuLeftNav.Items.FindItemByValue("SundaySchoolResources");
                    sitemapMenu.Visible = IsInRole("SundaySchoolTeacher");
                    imgContentTitleBar.ImageUrl = "~/Images/titleSeekingTruth.png";
                    break;
                case "MissionNews":
                    LeftNavigationChoice.SelectedIndex = viewMissionMenu.Index;                    
                    imgContentTitleBar.ImageUrl = "~/Images/titleMissionUpdates.png";
                    StaticMainImage1.Visible = true;
                    break;
                default:
                    throw new ArgumentException("Section code is invalid");
            }

            HeaderImage1.Visible = !StaticMainImage1.Visible;
        }

        string IDynamicPage.GetPageConfigurationControl()
        {
            return string.Empty;
        }

        string IDynamicPage.PageTypeName
        {
            get { return "File share"; }
        }
    }
}